<?php namespace App\Http\Controllers\Admin;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\News;
use App\Region;
use Illuminate\Http\Request;

class NewsController extends Controller
{
//显示内容
    public function getIndex(Request $request)
    {
        $title = trim($request->get('title', ''));
        $appends = [];

        $handler = News::orderBy('pubtime', 'DESC');

        if ($title) {
            $handler->where('title', 'like', '%' . $title . '%');
            $appends['title'] = $title;
        }

        $px = $request->get('px');
        $tuijian = $request->get('tuijian');
        $list = $handler->paginate(config('site.admin.pageSize'));


        return view('admin.news.index', [
            'list' => $list,
            'title' => $title,
            'tuijian' => $tuijian,
            'appends' => $appends,
            'px' => $px,
        ]);
    }

    public function getUpdate($id = 0)
    {
        $model = news::findOrNew($id);
        $cities = Region::orderBy('regionName','DESC')->lists('regionName','sysRegionId');
        return view('admin.news.update', [
            'model' => $model,
            'cities' => $cities,]);
    }


//提交获取的数据
    public function postUpdate(Request $request, $id = 0)
    {
        $ret = ['state' => 'fail'];
        $model = news::findOrNew($id);
        $data = $request->all();

        $attributes = [
            'title' => '新闻标题',
            'content' => '新闻内容',
        ];
        $rules = [
            'title' => 'required',
            'content' => 'required',
        ];

        $validator = \Validator::make($data, $rules, ['required' => ':attribute不能为空'], $attributes);
        if ($validator->fails()) {
            $message = $validator->messages();
            $ret['message'] = $message;
            foreach ($attributes as $k => $attr) {
                if ($message->has($k)) {
                    $ret['message'] = $message->first($k);
                    break;
                }
            }
        } else {
            $data['updatedate'] = date("Y-m-d H:i:s");
            if(0 == $id){
                $data['inputdate'] = $data['updatedate'];
            }
            if("正常" == $data['status']){
                $data['pubtime'] = $data['updatedate'];
            }
            $model->fill($data);
            $model->save();//写入数据库

            if ($model->newid) {
                $ret = ['state' => 'success', 'message' => '操作成功'];
            } else
                $ret['message'] = '保存出错';
        }

        return \Response::json($ret);
    }

    public function postDelete($id)
    {
        $ret = ['state' => 'fail', 'message' => '未知错误，请刷新重试'];
        if (News::destroy($id)) {
            $ret = ['state' => 'success', 'message' => '删除成功'];
        }
        return \Response::json($ret);
    }
}
